package com.encapi.framework.resolver;

import com.encapi.framework.annotation.DecryptParam;
import com.encapi.framework.core.CryptManager;
import org.springframework.core.MethodParameter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

public class DecParamHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Resource
    private CryptManager cryptManager;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(DecryptParam.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        // 获取 HttpServletRequest
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        if (request == null) {
            return null;
        }

        // 找对应参数
        String parameterName = methodParameter.getParameterName();
        if (!StringUtils.isEmpty(parameterName)) {
            String parameterValue = nativeWebRequest.getParameter(parameterName);
            if (parameterValue != null) {
                String strBody = parameterValue
                        .replaceAll(" ", "+");
                return cryptManager.decrypt(strBody, request, null);
            }
        }

        // 未找到对应参数
        return null;
    }

}
